package com.bw.lib_base.base


import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding

import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.util.LinkedList
import java.util.Queue


abstract class BaseActivity<VDB: ViewDataBinding,VM:BaseViewModel>:AppCompatActivity() {

    //1.获取当前类的泛型参数列表
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    // 2. 根视图容器
    private lateinit var contentView:View

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        // 获取系统默认根视图
        contentView = findViewById<View>(android.R.id.content)
    }

    override fun onResume() {
        super.onResume()
        
        //模板方法
        //1.建立UI
        setupUI()
        //2.获取数据
        fetchData()
        //3.观察接受数据
        observeData()
        //4.处理事件
        handleEvent()
    }
    private lateinit var premissionActionName:Array<String>

    protected abstract fun generatePremission(pageName:String):Array<String>


    /**
     * 使用广度优先搜索（BFS）设置视图及其子视图的可见性
     * @param rootView 根视图
     * @param visibility 设置的可见性（VISIBLE、INVISIBLE、GONE）
     */
    private fun setAllViewsVisibility(rootView: View?,btns:Array<String>) {
        if (rootView == null) return

        // 使用队列实现BFS
        val queue: Queue<View> = LinkedList()
        queue.offer(rootView) // 将根视图加入队列

        while (!queue.isEmpty()) {
            val currentView = queue.poll() // 获取队列中的当前视图

            if (currentView.id!=-1&&btns.contains(resources.getResourceEntryName(currentView.id))){
                currentView.visibility = View.GONE
            }


            // 如果当前视图是ViewGroup，将其子视图加入队列
            if (currentView is ViewGroup) {
                val viewGroup = currentView
                for (i in 0 until viewGroup.childCount) {
                    queue.offer(viewGroup.getChildAt(i)) // 将子视图加入队列
                }
            }
        }
    }



    protected val vm:VM by lazy {
        //读取第二个参数
        val clazz = type[1] as Class<VM>
        //根据传入的VideModel获取对应的VideModel对象
        ViewModelProvider(this)[clazz]
    }

    private var _binding: VDB? = null // 1. 私有可空变量
    protected val binding get() = _binding!!// 2. 受保护的非空属性

    fun onError(t:Throwable){
        Log.i("===",t.message.toString())
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val clazz = type[0] as Class<VDB> // 1. 获取绑定类类型
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)// 2. 获取inflate静态方法
        _binding = method.invoke(null,layoutInflater) as VDB // 3. 反射创建绑定对象
        setContentView(binding.root)  // 4. 设置内容视图

        //将viewModel作为观察者注册给activity
        this.lifecycle.addObserver(vm)
    }


    abstract fun setupUI()
    abstract fun fetchData()
    abstract fun observeData()
    abstract fun handleEvent()

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

    abstract val mLayoutResId: Int
}